package org.oos.dao.impl;

import static com.google.api.client.http.HttpMethod.POST;
import static org.oos.ApiUrlProvider.Offers;
import static org.oos.ApiUrlProvider.UserOffers;
import static org.oos.atom.AtomService.atomService;

import org.oos.ApiUrlProvider;
import org.oos.atom.AtomRequest;
import org.oos.atom.AtomResponse;
import org.oos.atom.OfferFeed;
import org.oos.atom.AtomService.HttpStatusException;
import org.oos.atom.entries.OfferEntry;
import org.oos.atom.entries.impl.OfferEntryImpl;
import org.oos.atom.impl.OfferFeedImpl;
import org.oos.dao.UserOfferDao;
import org.oos.dao.exceptions.CreationException;
import org.oos.dao.lists.impl.ReadOnlyDynamicList;
import org.oos.model.User;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.UrlEncodedContent;

public class UserOfferDaoImpl extends
		AbstractDao<OfferEntry, OfferFeed<OfferEntry>> implements UserOfferDao {

	private static final long serialVersionUID = 6147021955980888177L;
	private String userSlug = null;

	public UserOfferDaoImpl() {
		super(OfferFeedImpl.class, OfferEntryImpl.class);
	}

	@Override
	protected GenericUrl getFeedUrl() {
		if (userSlug != null) {
			return UserOffers.getUrl(userSlug);
		} else {
			return Offers.getUrl();
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	protected ReadOnlyDynamicList<OfferEntry, OfferFeed<OfferEntry>> getList(
			OfferFeed feed) {
		return new ReadOnlyDynamicList<OfferEntry, OfferFeed<OfferEntry>>(this,
				feed);
	}

	@Override
	public void setUser(User user) {
		this.userSlug = user.getSlug();
	}

	@Override
	public void setUserSlug(String slug) {
		this.userSlug = slug;
	}
	
	@Override
	public OfferEntry create() throws CreationException {
		try {
			UrlEncodedContent content = new UrlEncodedContent(null);
			AtomRequest request = requestBuilder() //
					.setUrl(getFeedUrl()) //
					.setContent(content) //
					.setHttpMethod(POST) //
					.build(); //
			AtomResponse<OfferEntry> response;
			response = atomService().execute(request, getEntryType());
			switch (response.getType()) {
			case Error:
				throw response.getThrowable();
			case Empty:
				return response.getResult();
			case Unknown:
			default:
				throw new IllegalArgumentException("Unknown error");
			}
		} catch (Throwable e) {
			CreationException exception;
			if (e instanceof HttpStatusException) {
				exception = new CreationException(e.getMessage());
				exception.setResponse(((HttpStatusException) e).getResponse());
			} else {
				exception = new CreationException(e);
			}
			throw exception;
		}
	}

}
